package cn.jobstart.service.impl;

import cn.jobstart.common.NumberUtil;
import cn.jobstart.common.SkList;
import cn.jobstart.common.StringUtil;
import cn.jobstart.common.enums.WhetherEnum;
import cn.jobstart.common.redis.RedisUtil;
import cn.jobstart.dao.IAdminDao;
import cn.jobstart.exception.ExceptionMessage;
import cn.jobstart.model.AdminPermissionGroup;
import cn.jobstart.model.Rights;
import cn.jobstart.modelExt.AdminExt;
import cn.jobstart.modelExt.AdminPermissionGroupExt;
import cn.jobstart.modelExt.RightsExt;
import cn.jobstart.pubInter.AbstractBaseService;
import cn.jobstart.pubInter.BaseSearch;
import cn.jobstart.pubInter.IBaseDao;
import cn.jobstart.pubInter.exception.BusinessException;
import cn.jobstart.pubInter.exception.SkException;
import cn.jobstart.searchExt.AdminSearchExt;
import cn.jobstart.searchExt.RightsSearchExt;
import cn.jobstart.service.IAdminPermissionGroupService;
import cn.jobstart.service.IAdminService;
import cn.jobstart.service.IGroupRightsService;
import cn.jobstart.service.IRightsService;
import cn.jobstart.web.common.SecurityUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author sunke
 * @Date 2023-09-06 15:00:20
 * @description AdminService      系统用户
 */
@Service(value = "adminService")
@Slf4j
public class AdminServiceImpl extends AbstractBaseService<AdminExt, AdminSearchExt, String> implements IAdminService {

    @Resource(name = "adminDao")
    private IAdminDao adminDao;

    @Resource
    private IAdminPermissionGroupService adminPermissionGroupService;
    @Resource
    private IGroupRightsService groupRightsService;
    @Resource
    private RedisUtil redisUtil;
    @Resource(name = "rightsService")
    private IRightsService rightsService;//权限

    @Override
    public IBaseDao<AdminExt, AdminSearchExt, String> getDao() {
        return adminDao;
    }


    /**
     * 更新已启用任务
     *
     * @param adminId
     */
    @Override
    public void addRunSubscriptionTask(String adminId) throws SkException {


        AdminExt admin = getDetail(adminId, new HashSet<>());

        if (NumberUtil.parseInt(admin.getTalentSubscriptionTaskMaxTotal()) < NumberUtil.parseInt(admin.getTalentSubscriptionTaskStartTotal())) {
            throw new BusinessException(ExceptionMessage.ADMIN_SUBSCRIPTION_MAX_ERROR);
        }
        admin.setTalentSubscriptionTaskStartTotal(NumberUtil.parseInt(admin.getTalentSubscriptionTaskStartTotal()) + 1);
        update(admin);


    }


    /**
     * 减少
     *
     * @param adminId
     * @throws SkException
     */
    @Override
    public void reduceRunSubscriptionTask(String adminId) throws SkException {

        AdminExt admin = getDetail(adminId, new HashSet<>());

        admin.setTalentSubscriptionTaskStartTotal(NumberUtil.parseInt(admin.getTalentSubscriptionTaskStartTotal()) - 1);
        update(admin);
    }

    /**
     * 检测员工是否还可以订阅
     *
     * @param adminId
     * @return
     */
    @Override
    public boolean canSubscriptionByAdminId(String adminId) {

        if (StringUtil.isNullOrEmpty(adminId)) {
            return false;
        }

        try {
            AdminExt admin = getDetail(adminId, new HashSet<>());
            return NumberUtil.parseInt(admin.getTalentSubscriptionTaskMaxTotal()) > NumberUtil.parseInt(admin.getTalentSubscriptionTaskStartTotal());


        } catch (SkException e) {

        }


        return false;
    }

    @Override
    public void fullOtherData(List<AdminExt> list, Set<String> fullConfigSet) {
        super.fullOtherData(list, fullConfigSet);
        fullAdminPermissionGroupList(list, fullConfigSet);
    }

    private void fullAdminPermissionGroupList(List<AdminExt> list, Set<String> fullConfigSet) {

        try {
            if (StringUtil.isNullOrEmpty(list)) {
                return;
            }
            List<String> adminIds = list.stream().map(AdminExt::getId).distinct().collect(Collectors.toList());

            List<AdminPermissionGroupExt> groupList = adminPermissionGroupService.getAllByInField(adminIds, AdminPermissionGroup.STAFF_ID, fullConfigSet);
            if (StringUtil.isNullOrEmpty(groupList)) {
                return;
            }
            Map<String, List<AdminPermissionGroupExt>> dataMap = groupList.stream().collect(Collectors.groupingBy(AdminPermissionGroupExt::getStaffId));
            list.stream().forEach(item -> {
                try {
                    item.setAdminPermissionGroupList(dataMap.get(item.getId()));
                } catch (Exception e) {

                }

            });


        } catch (Exception e) {

        }


    }

    @Override
    public void afterInsert(AdminExt obj) throws SkException {
        super.afterInsert(obj);
        List<AdminPermissionGroupExt> adminPermissionGroupList = obj.getAdminPermissionGroupList();

        if (StringUtil.isNullOrEmpty(adminPermissionGroupList)) {
            return;
        }

        adminPermissionGroupList.stream().forEach(item -> {

            item.setStaffId(obj.getId());


        });


        adminPermissionGroupService.batchInsert(adminPermissionGroupList);


    }

    @Override
    public void afterUpdate(AdminExt obj) throws SkException {
        super.afterUpdate(obj);
        clearRightsByStaffId(obj.getId());
        List<AdminPermissionGroupExt> adminPermissionGroupList = obj.getAdminPermissionGroupList();
        if (adminPermissionGroupList != null) {
            adminPermissionGroupService.clearByAdminId(obj.getId());
            adminPermissionGroupList.stream().forEach(item -> {
                item.setStaffId(obj.getId());
            });
            adminPermissionGroupService.batchInsert(adminPermissionGroupList);
        }


    }

    @Override
    public void afterDelete(String id) throws SkException {
        super.afterDelete(id);
        clearRightsByStaffId(id);
        adminPermissionGroupService.clearByAdminId(id);
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     * @throws SkException
     */
    @Override
    public AdminExt loginByUsernameAndPsw(String username, String password) throws SkException {

        if (StringUtil.isNullOrEmpty(username)) {
            throw new BusinessException(ExceptionMessage.EXIST_NO_CLIENT);
        }

        AdminExt admin = getInfoByUsername(username);

        if (StringUtil.isNullOrEmpty(admin)) {
            throw new BusinessException(ExceptionMessage.EXIST_NO_CLIENT);
        }
        password = SecurityUtil.generateUserPasswordByPswAndSalt(password, admin.getId());
        if (!admin.getPassword().equalsIgnoreCase(password)) {
            throw new BusinessException(ExceptionMessage.PSW_ERROR);
        }
        int locking = NumberUtil.parseInt(admin.getForbidden());
        if (locking == WhetherEnum.YES.getValue()) {
            throw new BusinessException(ExceptionMessage.LOCK);
        }
        return admin;


    }

    /**
     * 得到一个所有权限
     *
     * @param staffId
     * @return
     */
    @Override
    public List<String> getAllRightsIdsByStaffId(String staffId) {

        List<String> rightsIds = null;
        List<String> allRightsIds = SkList.getInstance();

        //自定义权限组的
        rightsIds = groupRightsService.getRightsIdsByStaffId(staffId);


        if (StringUtil.isNotObjEmpty(rightsIds)) {
            allRightsIds.addAll(rightsIds);
        }


        return allRightsIds;
    }

    /**
     * 根据用户名得到员工详情
     *
     * @param username
     * @return
     */
    @Override
    public AdminExt getInfoByUsername(String username) {
        if (StringUtil.isNullOrEmpty(username)) {
            return null;
        }

        return getDetailBySearch(AdminSearchExt.getInstance().setUsernameEq(username));
    }

    /**
     * 根据手机号码查询
     *
     * @param phone
     * @return
     */
    @Override
    public AdminExt getInfoByPhone(String phone) {

        if (StringUtil.isNullOrEmpty(phone)) {
            return null;
        }


        return getDetailBySearch(AdminSearchExt.getInstance().setPhoneEq(phone));
    }

    @Override
    public List<RightsExt> getAllRightsListByStaffId(String staffId, boolean cache) {
        try {

            if (cache) {
                List<Object> allList = redisUtil.lGet(staffId);
                if (StringUtil.isNotObjEmpty(allList)) {
                    log.debug("get staff rights from redis:" + staffId);
                    return allList.stream().map(item -> JSONObject.parseObject(StringUtil.toString(item), RightsExt.class)).collect(Collectors.toList());
                }
            }

            List<RightsExt> rightsList;
            List<String> rightsIds = getAllRightsIdsByStaffId(staffId);

            if (StringUtil.isNullOrEmpty(rightsIds)) {
                return null;
            }


            RightsSearchExt rightsSearch = RightsSearchExt.getInstance();
            rightsSearch.setIdIn(rightsIds);
            rightsSearch.setOrderBy(Rights.SORT_NUM);
            rightsSearch.setOrderDesc(BaseSearch.ASC_ORDER);

            rightsList = rightsService.getAllList(rightsSearch);

            clearRightsByStaffId(staffId);

            if (StringUtil.isNotObjEmpty(rightsList)) {
                rightsList.stream().forEach(rightsExt -> {
                    redisUtil.lSet(staffId, JSONObject.toJSONString(rightsExt));
                });
            }
          /*  else {//说明把权限全关了
                clearRightsByStaffId(staffId);
            }*/

            return rightsList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除某一个人的缓存权限
     *
     * @param staffId
     */
    @Override
    public void clearRightsByStaffId(String staffId) {

        log.debug("clear staff rights " + staffId);
        if (StringUtil.isNullOrEmpty(staffId)) {
            return;
        }

        try {
            redisUtil.lRemoveAll(staffId);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }


    }

}